import { type Directive } from 'vue';
import { useAuthStore } from '@/stores/module/auth';

// 指令核心逻辑
const permissionDirective: Directive = {
  mounted(el, binding) {
    const { value: permissionCode } = binding;
    const authStore = useAuthStore();
    
    if (!permissionCode) {
      console.error('v-permission requires a permission code');
      return;
    }

    // 获取当前路由名称（通过el获取组件实例）
    const routeName = getComponentRouteName(el);
    if (!routeName) return;

    // 检查权限
    const validButtons = authStore.mergedPermissions(routeName);
    if (!validButtons.includes(permissionCode)) {
      // 无权限时移除元素
      el.parentNode?.removeChild(el);
    }
  }
};

// 从组件实例中获取路由名称
function getComponentRouteName(el: HTMLElement): string | null {
  let current: any = el;
  while (current && !current.__vueParentComponent) {
    current = current.parentNode;
  }
  return current?.__vueParentComponent?.ctx?.$route?.name || null;
}

export default permissionDirective;